package org.freespace.utils;

import cn.hutool.http.HttpRequest;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Component;

import java.text.MessageFormat;

@Slf4j
@Component
public class ConsulUtil {
    private static String registerAppServerJsonTemplate = "{\"id\":\"%s\", \"name\": \"node-exporter-%s\",\"address\": \"%s\",\"port\": 9100,\"tags\": [\"pt\"],\"checks\": [{\"http\": \"http://%s:9100/metrics\", \"interval\": \"10s\"}]}";
    private static String registerStressMachineJsonTemplate = "{\"id\":\"%s\", \"name\": \"stressMahchine\",\"address\": \"%s\",\"port\": 9100,\"tags\": [\"pt\"],\"checks\": [{\"http\": \"http://%s:9100/metrics\", \"interval\": \"10s\"}]}";

    @Value("${consulRegisterUrl}")
    private String consulRegisterUrl;

    @Value("${consulDeregisterUrl}")
    private String consulDeregisterUrl;

    public void registerStressMachineToConsul(String ip, String jobId) {
        log.info("ip:{} jobId:{}", ip, jobId);
        String body = String.format(registerStressMachineJsonTemplate, jobId+"="+ip, ip, ip);
        String registerResponseBody =  HttpRequest.put(consulRegisterUrl).body(body).execute().body();
        log.info("registerResponseBody:{}", registerResponseBody);
    }

    public void registerAppServerToConsul(String ip, String jobId) {
        log.info("ip:{} jobId:{}", ip, jobId);
        String body = String.format(registerAppServerJsonTemplate, jobId+"="+ip, ip, ip, ip);
        String registerResponseBody =  HttpRequest.put(consulRegisterUrl).body(body).execute().body();
        log.info("registerResponseBody:{}", registerResponseBody);
    }


    public void deregisterFromConsul(String ip, String jobId) {
        log.info("ip:{} consulId:{}", ip, jobId+"="+ip);
        String url = MessageFormat.format(consulDeregisterUrl, new Object[]{jobId+"="+ip});
        String registerResponseBody =  HttpRequest.put(url).execute().body();
        log.info("deregisterFromConsul:{}", registerResponseBody);
    }
}
